'use client';

import { useState, useEffect, useRef } from 'react';

interface DownloadButtonProps {
  url: string;
  videoTitle?: string;
  className?: string;
  showText?: boolean;
}

export default function DownloadButton({ 
  url, 
  videoTitle = '视频', 
  className = '',
  showText = true
}: DownloadButtonProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [showGuide, setShowGuide] = useState(false);
  const [videoSources, setVideoSources] = useState<{url: string, type: string, quality?: string}[]>([]);
  const [showSourcesModal, setShowSourcesModal] = useState(false);
  const [videoFound, setVideoFound] = useState(false);
  const [scanning, setScanning] = useState(false);
  const playerWindowRef = useRef<Window | null>(null);
  
  // 记录是否已经嗅探到视频资源
  const hasDetectedRef = useRef(false);

  // 处理下载按钮点击
  const handleDownload = async () => {
    if (!url) return;
    
    setIsLoading(true);
    setError('');
    hasDetectedRef.current = false;
    setVideoSources([]);
    setVideoFound(false);
    
    try {
      // 提供两种选择：视频嗅探和常规下载指南
      setShowSourcesModal(true);
      
      // 去掉URL中可能存在的播放器前缀，获取原始视频URL
      const processed_url = url.indexOf('?url=') > -1 
        ? decodeURIComponent(url.split('?url=')[1]) 
        : url;
      
      // 在新窗口打开解析页面
      const playerWindow = window.open(url, '_blank');
      playerWindowRef.current = playerWindow;
      
      // 自动开始嗅探过程
      startVideoScan();
      
      // 开始嗅探视频资源
      if (playerWindow) {
        setTimeout(() => {
          setIsLoading(false);
        }, 1000);
      } else {
        setIsLoading(false);
        setError('弹窗被浏览器阻止，请允许弹窗后重试');
      }
    } catch (err) {
      console.error('打开视频页面出错:', err);
      setError('无法打开视频页面，请重试');
      setIsLoading(false);
    }
  };

  // 手动嗅探视频资源
  const startVideoScan = () => {
    setScanning(true);
    setVideoFound(false);
    
    // 检测视频源的具体URL
    let urlToScan = url;
    
    // 如果URL中包含解析接口前缀，提取原始URL
    if (url.indexOf('?url=') > -1) {
      try {
        urlToScan = decodeURIComponent(url.split('?url=')[1]);
      } catch (e) {
        console.error('URL解码错误:', e);
      }
    }
    
    // 嗅探特定视频源 - jx.xmflv.com 需要特殊处理
    if (url.includes('xmflv')) {
      // 客户端直接解析，不使用服务器代理
      setTimeout(() => {
        setVideoSources([
          { 
            url: url, 
            type: 'video/mp4', 
            quality: '解析播放页面 (推荐)' 
          },
          { 
            url: urlToScan, 
            type: detectVideoType(urlToScan), 
            quality: '原始视频链接' 
          }
        ]);
        setVideoFound(true);
        setScanning(false);
      }, 1500);
      return;
    }
    
    // 尝试推测可能的不同清晰度视频链接
    const detectPossibleVideoFormats = (baseUrl: string) => {
      const possibleFormats: {url: string, type: string, quality: string}[] = [];
      
      // 原始链接作为基础链接
      possibleFormats.push({ 
        url: baseUrl, 
        type: detectVideoType(baseUrl), 
        quality: '直接播放链接' 
      });
      
      // 添加视频解析站链接选项
      if (!baseUrl.includes('jx.xmflv.com')) {
        possibleFormats.push({ 
          url: `https://jx.xmflv.com/?url=${encodeURIComponent(baseUrl)}`, 
          type: 'video/mp4', 
          quality: '通过解析站播放 (推荐)' 
        });
      }
      
      // 返回所有可能的格式
      return possibleFormats;
    };
    
    // 尝试检测视频MIME类型
    const detectVideoType = (url: string) => {
      if (url.includes('.mp4')) return 'video/mp4';
      if (url.includes('.m3u8')) return 'application/x-mpegURL';
      if (url.includes('.flv')) return 'video/x-flv';
      if (url.includes('.webm')) return 'video/webm';
      // 默认返回mp4类型
      return 'video/mp4';
    };
    
    // 通用解析方法
    setTimeout(() => {
      setVideoSources(detectPossibleVideoFormats(urlToScan));
      setVideoFound(true);
      setScanning(false);
    }, 1500);
  };

  // 下载特定视频源
  const downloadVideoSource = (sourceUrl: string, quality: string = '默认') => {
    try {
      setShowSourcesModal(false);
      setIsLoading(true);
      
      // 创建一个新窗口打开视频链接
      const videoWindow = window.open(sourceUrl, '_blank');
      
      if (!videoWindow) {
        setError('无法打开视频窗口，请允许弹窗后重试');
      }
      
      // 显示下载指南
      setTimeout(() => {
        setShowGuide(true);
        setIsLoading(false);
      }, 1000);
      
    } catch (err) {
      console.error('打开视频链接失败:', err);
      setIsLoading(false);
      setShowGuide(true);
    }
  };

  // 显示常规下载指南
  const showDownloadGuide = () => {
    setShowSourcesModal(false);
    setShowGuide(true);
  };

  return (
    <div className={`relative ${className}`}>
      <button
        onClick={handleDownload}
        disabled={isLoading || !url}
        className="flex items-center justify-center px-3 py-2 bg-green-500 hover:bg-green-600 text-white rounded-md transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed"
        title="下载视频"
      >
        {isLoading ? (
          <>
            <svg className="animate-spin h-4 w-4 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {showText && <span>处理中...</span>}
          </>
        ) : (
          <>
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 mr-1">
              <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
            </svg>
            {showText && <span>下载视频</span>}
          </>
        )}
      </button>
      
      {error && (
        <div className="absolute top-full left-0 mt-1 w-full bg-red-100 text-red-700 px-2 py-1 rounded text-xs">
          {error}
        </div>
      )}

      {showSourcesModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowSourcesModal(false)}>
          <div className="bg-white dark:bg-gray-800 p-5 rounded-lg max-w-md w-full text-black dark:text-white" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-bold">视频下载助手</h3>
              <button 
                onClick={() => setShowSourcesModal(false)}
                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            
            <div className="mb-5">
              <h4 className="font-semibold mb-2">视频标题: {videoTitle}</h4>
              <p className="text-sm text-gray-600 dark:text-gray-400">原始链接: {url.length > 40 ? url.substring(0, 40) + '...' : url}</p>
            </div>
            
            <div className="border-t border-b border-gray-200 dark:border-gray-700 py-4 mb-4">
              {!scanning && !videoFound && (
                <div className="space-y-4">
                  <button 
                    onClick={startVideoScan}
                    className="w-full py-3 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors flex items-center justify-center"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 mr-2">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
                    </svg>
                    嗅探视频源 (推荐)
                  </button>
                  
                  <button 
                    onClick={showDownloadGuide}
                    className="w-full py-3 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-white rounded-md transition-colors flex items-center justify-center"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5 mr-2">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" />
                    </svg>
                    查看下载指南
                  </button>
                </div>
              )}
              
              {scanning && (
                <div className="text-center py-4">
                  <div className="animate-spin h-10 w-10 border-4 border-blue-500 border-t-transparent rounded-full mx-auto mb-3"></div>
                  <p>正在嗅探视频资源，请稍候...</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">扫描可能需要几秒钟时间</p>
                </div>
              )}
              
              {videoFound && (
                <div>
                  <h5 className="font-medium mb-3">找到以下视频源:</h5>
                  <ul className="space-y-2">
                    {videoSources.map((source, index) => (
                      <li key={index} className={`border ${index === 0 ? 'border-green-300 dark:border-green-700 bg-green-50 dark:bg-green-900/20' : 'border-gray-200 dark:border-gray-700'} rounded-md p-3`}>
                        <div className="flex justify-between items-center mb-1">
                          <span className={`font-medium ${index === 0 ? 'text-green-700 dark:text-green-400' : ''}`}>
                            {source.quality || '默认'} 
                            {index === 0 && <span className="ml-1 text-xs bg-green-100 dark:bg-green-800 text-green-800 dark:text-green-200 px-1.5 py-0.5 rounded-full">推荐</span>}
                          </span>
                          <span className="text-xs px-2 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">
                            {source.url.includes('/api/download') ? '服务器代理' : '直接地址'}
                          </span>
                        </div>
                        <div className="text-xs text-gray-500 truncate mt-1 mb-2">
                          {source.url.length > 60 ? source.url.substring(0, 60) + '...' : source.url}
                        </div>
                        <div className="flex justify-end items-center mt-2">
                          <button
                            onClick={() => downloadVideoSource(source.url, source.quality)}
                            className={`px-3 py-1.5 ${index === 0 ? 'bg-green-500 hover:bg-green-600' : 'bg-blue-500 hover:bg-blue-600'} text-white text-sm rounded flex items-center`}
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
                            </svg>
                            下载
                          </button>
                        </div>
                      </li>
                    ))}
                  </ul>
                  
                  <div className="mt-4 bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded text-xs text-yellow-800 dark:text-yellow-200">
                    <p className="flex items-start">
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1 flex-shrink-0 mt-0.5">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                      </svg>
                      <span>
                        点击【下载】将在新窗口打开视频页面。视频加载完成后，请参照下载指南手动保存视频。
                      </span>
                    </p>
                  </div>
                </div>
              )}
            </div>
            
            <div className="text-xs text-center text-gray-500 dark:text-gray-400">
              这是一个模拟的视频下载助手界面，实际功能受浏览器安全策略限制
            </div>
          </div>
        </div>
      )}

      {showGuide && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowGuide(false)}>
          <div className="bg-white dark:bg-gray-800 p-5 rounded-lg max-w-md text-black dark:text-white" onClick={e => e.stopPropagation()}>
            <h3 className="text-lg font-bold mb-3">如何下载视频</h3>
            
            <div className="mt-2 bg-yellow-50 dark:bg-yellow-900/30 p-3 rounded-md text-sm">
              <h4 className="font-semibold mb-1">使用jx.xmflv.com解析接口</h4>
              <ol className="list-decimal pl-4 space-y-2">
                <li>视频加载完成后，<strong>点击播放器底部或右下角的【下载】按钮</strong></li>
                <li>如果没有看到下载按钮，请查看控制面板：
                  <ul className="list-disc pl-4 mt-1 text-xs">
                    <li>在视频播放过程中底部会显示控制菜单</li>
                    <li>可能包含【播放速度】【画面比例】【画面翻转】等选项</li>
                    <li>寻找菜单中的【下载】或【视频下载】选项</li>
                  </ul>
                </li>
                <li>如果控制面板中没有下载选项：
                  <ul className="list-disc pl-4 mt-1 text-xs">
                    <li>视频可能受到保护，无法直接下载</li>
                    <li>尝试使用专业视频捕获软件或浏览器扩展</li>
                    <li>部分浏览器(如Firefox)可能有内置视频捕获功能</li>
                  </ul>
                </li>
              </ol>
              <div className="mt-2 text-xs border-t border-yellow-200 dark:border-yellow-800 pt-2">
                <p className="font-semibold">快捷键提示：</p>
                <p>空格键 - 播放/暂停 | F - 全屏 | M - 静音</p>
              </div>
            </div>

            <div className="mt-4 bg-blue-50 dark:bg-blue-900/30 p-3 rounded-md text-xs">
              <h4 className="font-semibold mb-1">使用浏览器开发者工具下载</h4>
              <ol className="list-decimal pl-4 space-y-1">
                <li>在视频页面按<strong>F12</strong>打开开发者工具</li>
                <li>切换到【网络】(Network)标签</li>
                <li>在过滤器中输入"<strong>mp4</strong>"或"<strong>m3u8</strong>"以过滤视频文件</li>
                <li>刷新页面，开始播放视频，观察网络请求</li>
                <li>找到视频文件后，<strong>右键选择"在新标签页中打开"</strong></li>
                <li>视频文件加载后，右键选择"<strong>另存为</strong>"下载</li>
              </ol>
            </div>

            <div className="mt-4 bg-green-50 dark:bg-green-900/20 p-3 rounded-md text-xs">
              <h4 className="font-semibold mb-1">使用屏幕录制方法</h4>
              <p className="mb-2">如果上述方法无法下载，您可以：</p>
              <ol className="list-decimal pl-4 space-y-1">
                <li>将视频全屏播放</li>
                <li>使用系统自带的屏幕录制功能（Win10按<strong>Win+G</strong>打开）</li>
                <li>或使用第三方录屏软件记录播放内容</li>
              </ol>
            </div>
            
            <button 
              className="mt-5 w-full py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded transition-colors"
              onClick={() => setShowGuide(false)}
            >
              我知道了
            </button>
          </div>
        </div>
      )}
    </div>
  );
} 